package com.tigger.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InetAddressUnit {

    final static Logger LOGGER = LoggerFactory.getLogger(InetAddressUnit.class);

    /**
     * 获取机器IP
     *
     * @return
     */
    public static String getLocalHostIp() {
        if (isWindowsOS()) {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                LOGGER.info("Error when getting windows host ip address: <{}>.", e.getMessage());
            }
        } else {
            InetAddress inetAddress = getLinuxLocalHost();
            if (null != inetAddress) return inetAddress.getHostAddress();
        }
        return null;
    }

    /**
     * 判断操作系统是否是windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }


    /**
     * 获取linux系统的InetAddress对象
     *
     * @return
     */
    public static InetAddress getLinuxLocalHost() {
        try {
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                if (addresses.hasMoreElements()) {
                    return addresses.nextElement();
                }
            }
        } catch (SocketException e) {
            LOGGER.info("Error when getting linux host ip address: <{}>.", e.getMessage());
        }
        return null;
    }
}
